import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an8 from '@mmstudio/an000008';
import an48 from '@mmstudio/an000048';
import { tbfdgroup } from '../../../../atoms/db';

const logger = anylogger('pages/api/admin/groups/add.api');

export type Result = {
	ok: true;
	id: string;
} | {
	ok: false;
	message: string;
};

export type Message = Pick<ITbfdgroup, 'pid' | 'name'>;

/**
 * 新增组别服务
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const body = req.body as Message;
		//数据校验
		if (!body
			|| !body.name
		) {
			res.status(200).json({
				ok: false,
				message: '组别不能为空，请填写完整'
			});
			return;
		}
		//查重
		const r = await tbfdgroup().first('*').where({
			name: body.name, pid: body.pid || ''
		});
		if (r) {
			res.status(200).json({ ok: false, message: '组别已存在' });
			return;
		}

		const id = an8();
		await tbfdgroup().insert({
			name: body.name,
			groupid: id,
			pid: body.pid || ''
		});
		res.status(200).json({
			ok: true,
			id
		});
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
